/**
 * 
 */
package zuoshen;

import java.util.ArrayList;
import java.util.Scanner;
import java.util.Stack;

/**
 * @author zhongfang
 *
 */
public class 京东环状链表看见对数 {

	static class Node {
		public Node(int i, int j) {
			this.val = i;
			this.cnt = j;
		}

		int val;
		long cnt;
		int left = -1;
		int right = -1;
		boolean isValid = true;
	}

	public static long getCount(int a[]) {
		ArrayList<Node> list = new ArrayList<>();
		int max = 0;
		int index = -1;
		for (int i = 0; i < a.length; i++) {
			if (i != 0 && a[i] == a[i - 1]) {
				list.get(list.size() - 1).cnt++;
			} else {
				list.add(new Node(a[i], 1));
			}
			if (index == -1 || max < a[i]) {
				max = a[i];
				index = list.size() - 1;
			}
		}
		Stack<Node> stack = new Stack<>();
		stack.push(list.get(index));
		int cnt = 1;
		int len = list.size();
		index = getNext(index, len);
		while (cnt < len) {
			while (list.get(index).val > stack.peek().val) {// 当前>栈顶，则弹出
				Node pre = stack.pop();
				pre.right = list.get(index).val;
				if (!stack.isEmpty()) {
					pre.left = stack.peek().val;
				}
			}
			if (stack.isEmpty() || list.get(index).val < stack.peek().val) {// 空或者当前<栈顶，则压入
				stack.push(list.get(index));
			} else {// 合并
				stack.peek().cnt += list.get(index).cnt;
				list.get(index).isValid = false;
			}

			index = getNext(index, len);
			cnt++;
		}
		// 处理栈内数据
		while (!stack.isEmpty()) {
			Node node = stack.pop();
			if (stack.size() > 1) {
				node.right = max;// 右侧最近的最大值是栈底值，通过环状绕回去了
				node.left = stack.peek().val;
			} else if (stack.size() == 1) {
				node.left = stack.peek().val;
				if (stack.peek().cnt != 1) {
					node.right = stack.peek().val;
				}
			}
		}
		long count = 0;
		for (Node node : list) {
			if (!node.isValid)
				continue;
			count += node.cnt * (node.cnt - 1) / 2;
			if (node.left != -1) {
				count += node.cnt;
			}
			if (node.right != -1) {
				count += node.cnt;
			}
		}
		return count;
	}

	private static int getNext(int maxIndex, int len) {
		maxIndex++;
		if (maxIndex == len) {
			return 0;
		}
		return maxIndex;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		while (scanner.hasNext()) {
			int n = scanner.nextInt();
			int a[] = new int[n];
			for (int i = 0; i < n; i++) {
				a[i] = scanner.nextInt();
			}
			System.out.println(getCount(a));
		}
	}

}
